package mygang.controller.manager;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mygang.controller.AbstractController;
import mygang.helper.ControllerHelper;
import mygang.helper.JsonHelper;
import mygang.helper.Utils;
import mygang.model.constructor.EntityModel;
import mygang.model.constructor.TableWizardModel;
import mygang.service.manager.EntityService;
import mygang.service.manager.TableService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 20/03/2013
 */
@Controller
@RequestMapping(AbstractController.MANAGE_ENTITY)
public class EntityController extends AbstractManageController<EntityService, EntityModel> {

    private static final Logger log = Logger.getLogger(EntityController.class.toString());
    
    @Autowired
    TableService tableService;
    
    @RequestMapping(value = "/getEntityColumns", method = RequestMethod.POST)
    public void getTableColumns(@RequestParam(required = true, value = "id") Long id, HttpServletResponse response) throws IOException {
        try {
            EntityModel entity = getService().getById(id);
            TableWizardModel table = entity.getTable();
            JsonHelper.prepareJsonResponse(Utils.convertToOptions(tableService.getTableColumns(table.getName())), response);
        } catch (Exception ex) {
            ControllerHelper.handleException(ex, response);
        }
    }
    
    @Override
    EntityModel prepareObject(HttpServletRequest request) throws Exception {
        String tempId = request.getParameter("id");
        Long id = tempId!=null && !tempId.isEmpty() ? new Long(request.getParameter("id")) : null;
        
        String name = request.getParameter("name");
        if(name==null || name.isEmpty()) {
            throw new Exception("Name is not specified");
        }
        
        Long tableId = new Long(request.getParameter("tableId"));
        if(tableId==null) {
            throw new Exception("Table is not selected");
        }
        TableWizardModel table = tableService.getById(tableId.longValue());
        EntityModel model;
        if(id==null){
            model = new EntityModel(name, table);
        } else {
            model = new EntityModel(id.longValue() ,name, table);
        }
        
        return model;
    }

    @Override
    String getLink() {
        return MANAGE_ENTITY;
    }

}